package com.ssy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssy.common.utils.PageResult;
import com.ssy.system.mapper.LogMapper;
import com.ssy.system.mapper.UserMapper;
import com.ssy.system.pojo.Log;
import com.ssy.system.pojo.User;
import com.ssy.system.service.ILogService;
import com.ssy.system.vo.LogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sunshuaiyong
 * @ClassName ILogServiceImpl
 * @description: TODO
 * @date 2021/11/1 14:29
 */
@Service
public class ILogServiceImpl extends ServiceImpl<LogMapper, Log> implements ILogService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult selectLogByPage(LogVo logVo) {
        Page<Log> page = new Page<>(logVo.getPage(), logVo.getLimit());
        List<User> users = this.userMapper.selectList(new LambdaQueryWrapper<User>()
                .select(User::getId)
                .eq(User::getState, 1)
                .like(StringUtils.hasText(logVo.getRealName()), User::getRealName, logVo.getRealName())
                .eq(StringUtils.hasText(logVo.getUserName()), User::getUserName, logVo.getUserName())
                .eq(logVo.getLoginType() != null, User::getType, logVo.getLoginType()));

        List<Integer> ids = new ArrayList<>();
        for (User user : users) {
            ids.add(user.getId());
        }

        if (ids.size() == 0) {
            ids.add(-1);
        }

        IPage<Log> logIPage = this.logMapper.selectPage(page, new LambdaQueryWrapper<Log>()
                .in(Log::getUserId, ids)
                .eq(logVo.getLoginStart() != null, Log::getLoginStart, logVo.getLoginStart())
                .ge(logVo.getBeginTime() != null, Log::getLoginTime, logVo.getBeginTime())
                .le(logVo.getEndTime() != null, Log::getLoginTime, logVo.getEndTime())
                .orderByDesc(Log::getLoginTime)
        );

        //数据填充
        List<Log> logList = logIPage.getRecords();
        for (Log log1 : logList) {
            User user = this.userMapper.selectById(log1.getUserId());
            log1.setRealName(user.getRealName());
            log1.setUserName(user.getUserName());
            log1.setLoginType(user.getType());
        }

        return new PageResult(logIPage.getTotal(), logList);
    }


    @Override
    public void insertLog(Log log) {
        this.logMapper.insert(log);
    }
}
